package io.github.wslxm.springbootplus2.file.strategy.service.impl;

import io.github.wslxm.springbootplus2.core.config.error.ErrorException;
import io.github.wslxm.springbootplus2.core.result.ResultType;
import io.github.wslxm.springbootplus2.core.utils.XjFileUtil;
import io.github.wslxm.springbootplus2.file.constant.RenameRuleEnum;
import io.github.wslxm.springbootplus2.file.constant.RequestConst;
import io.github.wslxm.springbootplus2.file.properties.FileProperties;
import io.github.wslxm.springbootplus2.file.strategy.service.FileStrategy;
import io.github.wslxm.springbootplus2.file.util.FileDownloadUtil;
import io.github.wslxm.springbootplus2.file.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;


/**
 * 阿里云oss 文件上传
 *
 * @author wangsong
 * @version 1.0.0
 * @mail 1720696548@qq.com
 * @date 2022/10/15 0015 18:18
 */
@Service
public class AliYunOssFileStrategy implements FileStrategy {

    @Autowired
    private OssUtil ossUtil;

    /**
     * 文件上传配置
     */
    @Autowired
    private FileProperties fileProperties;


    @Override
    public String upload(InputStream inputStream, String filePath, String fileName, String renameRule) {
        return ossUtil.upload(fileProperties.getAliyunOss().getPath(), filePath, fileName, inputStream);
    }

    @Override
    public String downloadUpload(String url, String filePath, String newFileName) {
        // 判断是否可访问
        boolean isUrlAccess = FileDownloadUtil.checkUrlAccess(url);
        if (!isUrlAccess) {
            throw new ErrorException( ResultType.FILE_URL_NO_VISIT);
        }
        // 下载
        InputStream inputStream = XjFileUtil.getInputStreamByUrl(url);
        // 上传
        return upload(inputStream, filePath, newFileName, RenameRuleEnum.NO.getValue());
    }


    @Override
    public boolean del(String filePath) {
        // 去除访问地址
        if (filePath.contains(RequestConst.HTTP) || filePath.contains(RequestConst.HTTPS)) {
            filePath = filePath.replace(RequestConst.HTTP, "").replace(RequestConst.HTTPS, "");
            filePath = filePath.substring(filePath.indexOf("/") + 1);
        }
        return ossUtil.deleteObject(filePath);
    }

    @Override
    public boolean delFolder(String filePath) {
        return ossUtil.deleteObjectFolde(filePath);
    }
}
